<template>
  <div class="login">
    <div class="login-bg"></div>
    <div class="login-container">
      <div class="login-box">
        <div class="view-account-top">
          <div class="view-account-top-logo">
            <!--            <img :src="globalConfiguration.logoImg" alt="" />-->
          </div>
          <div class="view-account-top-title">欢迎使用{{ globalConfiguration.logoName }}</div>
        </div>
        <br/>
        <n-form
          ref="loginFormRef"
          label-placement="left"
          :model="loginForm"
          :rules="formRules"
        >
          <n-form-item path="account">
            <n-input @change="onBlurAccountEvent" v-model:value="loginForm.account"
                     placeholder="请输入登录账号">
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <PersonOutline/>
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item path="password">
            <n-input
              v-model:value="loginForm.password"
              type="password"
              showPasswordOn="click"
              @keydown.enter="onLoginBtnEvent"
              placeholder="请输入密码"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <LockClosedOutline/>
                </n-icon>
              </template>
            </n-input>

          </n-form-item>
          <n-form-item path="password" v-if="requireVerificationCode">
            <n-input style="width: calc(100% - 85px)" @keydown.enter="onLoginBtnEvent"
                     v-model:value="loginForm.verificationCode"
                     type="text"
                     showPasswordOn="click"
                     placeholder="请输入验证码"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <LockClosedOutline/>
                </n-icon>
              </template>
            </n-input>
            <n-image
              style="width: 80px;height: 35px;margin-left: 5px"
              @click="onVerificationCodeEvent"
              :src="imgVerificationCode"
              preview-disabled
            />
          </n-form-item>
          <!--          <n-form-item class="default-color">-->
          <!--            <div class="flex justify-between">-->
          <!--              <div class="flex-initial">-->
          <!--                <n-checkbox v-model:checked="autoLogin">自动登录</n-checkbox>-->
          <!--              </div>-->
          <!--              <div class="flex-initial order-last">-->
          <!--                <a href="javascript:">忘记密码</a>-->
          <!--              </div>-->
          <!--            </div>-->
          <!--          </n-form-item>-->
          <n-form-item class="mt-5">
            <n-button type="primary" @click="onLoginBtnEvent" :loading="loading" block>
              立即登录
            </n-button>
          </n-form-item>
          <n-form-item path="checkboxValue">
            <n-checkbox v-model:checked="loginForm.rememberMe" checked-value="1">
              记住登录状态(7天内本客户端免登录)
            </n-checkbox>
          </n-form-item>
          <!--          <n-form-item class="default-color">-->
          <!--            <div class="flex view-account-other">-->
          <!--              <div class="flex-initial">-->
          <!--                <span>其它登录方式</span>-->
          <!--              </div>-->
          <!--              <div class="flex-initial mx-2">-->
          <!--                <a href="javascript:">-->
          <!--                  <n-icon size="24" color="#2d8cf0">-->
          <!--                    <LogoGithub />-->
          <!--                  </n-icon>-->
          <!--                </a>-->
          <!--              </div>-->
          <!--              <div class="flex-initial mx-2">-->
          <!--                <a href="javascript:">-->
          <!--                  <n-icon size="24" color="#2d8cf0">-->
          <!--                    <LogoFacebook />-->
          <!--                  </n-icon>-->
          <!--                </a>-->
          <!--              </div>-->
          <!--              <div class="flex-initial" style="margin-left: auto">-->
          <!--                <a href="javascript:">注册账号</a>-->
          <!--              </div>-->
          <!--            </div>-->
          <!--          </n-form-item>-->
        </n-form>
      </div>

    </div>
  </div>
</template>
<script lang="ts">
import {defineComponent, onMounted, reactive, ref} from "vue";
import loginApi, {LoginAccountRequest, LoginAccountResponse} from "@/api/loginApi";
import {ApiResponse} from "@/api/types/ApiResponse";
import {useRouter} from "vue-router";
import md5 from "js-md5";
import SlashAppContext, {GlobalApplicationConfiguration} from "@/context/SlashAppContext";
import {LockClosedOutline, PersonOutline} from "@vicons/ionicons5";
import tokenApi from "@/api/tokenApi";

export default defineComponent({
  components: {
    PersonOutline,
    LockClosedOutline
  },
  setup() {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const router = useRouter();
    const loginFormRef = ref<any>();
    const loading = ref<boolean>(false);
    const globalConfiguration = SlashAppContext.getGlobalApplicationConfiguration();

    /*登录表单*/
    const loginForm = reactive({
      account: GlobalApplicationConfiguration.profile != "dev" ? "" : "admin",
      password: GlobalApplicationConfiguration.profile != "dev" ? "" : "e10adc3949ba59abbe56e057f20f883e",
      verificationCode: "",
      rememberMe: 0
    });
    /*视图控制*/
    const ctrl = reactive({
      logging: false,
      loginBtnLabel: "立 即 登 录",
      logoName: GlobalApplicationConfiguration.logoName
    });
    const formRules = reactive({
      account: [{required: true, message: "请输入登录账号", trigger: "blur"}],
      password: [{required: true, message: "请输入登录密码", trigger: "blur"}]
    });
    const imgVerificationCode = ref<string>("");
    const requireVerificationCode = ref<boolean>(false);
    const onBlurAccountEvent = async () => {
      await checkRequireVerificationCodeAndRefreshImage();
    };
    const checkRequireVerificationCodeAndRefreshImage = async () => {
      const requireVerificationCode = await doIsRequireVerificationCode();
      if (requireVerificationCode) {
        await doRefreshImageVerificationCode();
      }
    };
    const doInit = async () => {
      await SlashAppContext.isRouterReady();
      console.log("请求自动登录");
      const loginSuccess = await loginApi.doRefreshTokenLogin();
      if (loginSuccess) {
        SlashAppContext.getRouter()?.push({
          path: SlashAppContext.getAppConfig().loginSuccessRouterPath,
          query: {
            slashInnerTitle: SlashAppContext.getAppConfig().loginSuccessRouterTitle,
            slashInnerOpen: SlashAppContext.getAppConfig().loginSuccessInnerOpen ? 1 : 0
          }
        });
      }
    };
    /**
     * 处理登录逻辑
     * @param loginFormRef
     */
    const onLoginBtnEvent = async () => {
      console.log(loginFormRef);
      await loginFormRef.value.validate();
      loading.value = true;
      setTimeout(async () => {
        try {
          await doLogin();
        } finally {
          loading.value = false;
        }
      }, 500);

    };
    /**
     * 刷新图片验证码
     */
    const doRefreshImageVerificationCode = async () => {
      const {data} = await loginApi.selectVerificationCode(loginForm.account);
      imgVerificationCode.value = data.img;
    };
    const onVerificationCodeEvent = async () => {
      await doRefreshImageVerificationCode();
    };
    const doIsRequireVerificationCode = async (): Promise<boolean> => {
      const {data} = await loginApi.isRequireVerificationCode(loginForm.account);
      requireVerificationCode.value = data;
      return data;
    };
    onMounted(() => {
      doInit();
    });
    /**
     * 登录业务处理
     */
    const doLogin = async () => {
      let loginData: LoginAccountRequest = JSON.parse(JSON.stringify(loginForm));
      loginData.password = md5(loginData.password);
      await loginApi.loginAccount(loginData as LoginAccountRequest)
        // const data: LoginAccountResponse = msg.data;
        // tokenApi.setToken(data.token, data.expires);
        // SlashAppContext.getRouter()?.push({
        //   path: SlashAppContext.getAppConfig().loginSuccessRouterPath,
        //   query: {
        //     slashInnerTitle: SlashAppContext.getAppConfig().loginSuccessRouterTitle,
        //     slashInnerOpen: SlashAppContext.getAppConfig().loginSuccessInnerOpen ? 1 : 0
        //   }
        // });
        .then((msg: ApiResponse<LoginAccountResponse>) => {
          let data: LoginAccountResponse = msg.data;
          tokenApi.setToken(data.token, data.expires);
          if (data.refreshToken) {
            tokenApi.setRefreshToken(data.refreshToken.token, data.expires);
          }
          SlashAppContext.getRouter()?.push({
            path: SlashAppContext.getAppConfig().loginSuccessRouterPath,
            query: {
              slashInnerTitle: SlashAppContext.getAppConfig().loginSuccessRouterTitle,
              slashInnerOpen: SlashAppContext.getAppConfig().loginSuccessInnerOpen ? 1 : 0
            }
          });
        }).catch((msg: ApiResponse<any>) => {
          setTimeout(() => {
            checkRequireVerificationCodeAndRefreshImage();
          }, 500);
        });

      // .finally(() => {
      //
      // });
    };
    return {
      loginFormRef,
      formRules,
      loginForm,
      ctrl,
      loading,
      onLoginBtnEvent,
      globalConfiguration,
      requireVerificationCode,
      onBlurAccountEvent,
      imgVerificationCode,
      onVerificationCodeEvent
    };
  }
});
</script>


<style lang="less" scoped>
.login {
  overflow: hidden;

  .login-bg {
    position: fixed;
    height: 100%;
    width: 100%;
    transform: scale(1.2);
    background-image: url('../../../public/bg.jpg');
    @blur: 10px;
    -webkit-filter: blur(@blur); /* Chrome, Opera */
    -moz-filter: blur(@blur);
    -ms-filter: blur(@blur);
    filter: blur(@blur);
    z-index: 0;

    &:before {
      content: '';
      position: absolute;
      height: 100%;
      width: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      top: 0;
      left: 0;
      z-index: -1;
    }
  }

  .login-container {
    display: block;
    position: fixed;
    width: 100%;
    color: white;
    height: 100%;
    z-index: 9;

    .login-box {
      background: var(--slash-layer-bg-color);
      margin: 15vh auto;
      width: fit-content;
      min-width: 400px;
      padding: 10px 40px;
      border-radius: 5px;

      .view-account-top {
        font-size: 24px;
        text-align: center;
        margin: 10px 0px;

        &-title {
          color: black;
        }
      }
    }

  }

}
</style>
